import React from 'react'

// 导入样式文件
import './index.css'

export default class App extends React.Component {
  state = {
    // 评论列表
    comments: [
      { id: 1, name: '亚瑟', content: '沙发！！！' },
      { id: 2, name: '妲己', content: '板凳~' },
      { id: 3, name: '程咬金', content: '楼主好人' }
    ],
    // 评论人
    user: '',
    // 评论内容
    content: ''
  }

  renderList = () => {
    if (this.state.comments.length === 0) {
      return (<div className="no-comment">暂无评论，快去评论吧~</div>)
    }

    return (
      <ul>
        {
          this.state.comments.map(item => (
            <li key={item.id}>
              <h3>评论人：{item.name}</h3>
              <p>评论内容：{item.content}</p>
            </li>
          ))
        }
      </ul>
    )
  }

  change = (e) => {
    // 获取元素对象
    const target = e.target
    // 根据类型获取值
    const value = target.type === 'checkbox' ? target.checked : target.value

    // 获取表单名字 name 属性
    const name = target.name
    // 将取到结果复制给 state
    this.setState({
      [name]: value
    })
  }

  render() {
    const { user, content } = this.state
    return (
      <div className="app">
        <div>
          <input className="user" type="text" placeholder="请输入评论人" name="user" value={user} onChange={this.change} />
          <br />
          <textarea
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
            name="content"
            value={content}
            onChange={this.change}
          />
          <br />
          <button>发表评论</button>
        </div>

        {/* 评论区域 */}
        {this.renderList()}
      </div>
    )
  }
}